package com.sqx.modules.recovery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.recovery.dao.GoodsRecoveryDao;
import com.sqx.modules.recovery.dao.GoodsRecoveryUserDao;
import com.sqx.modules.recovery.dao.GoodsSpecificationsDao;
import com.sqx.modules.recovery.entity.GoodsRecovery;
import com.sqx.modules.recovery.entity.GoodsRecoveryUser;
import com.sqx.modules.recovery.entity.GoodsSpecifications;
import com.sqx.modules.recovery.service.GoodsRecoveryService;
import com.sqx.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author Admin
 * @description 针对表【goods_recovery(二手物品回收估价表)】的数据库操作Service实现
 * @createDate 2024-06-28 10:50:20
 */
@Service
public class GoodsRecoveryServiceImpl extends ServiceImpl<GoodsRecoveryDao, GoodsRecovery>
        implements GoodsRecoveryService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private GoodsSpecificationsDao goodsSpecificationsDao;

    @Autowired
    private GoodsRecoveryUserDao goodsRecoveryUserDao;

    @Override
    public Result saveGoodsRecovery(GoodsRecovery goodsRecovery) {
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return Result.error("该用户不存在或未登录");
        }
        // 对商品名进行标准化处理
        String normalizedGoodsName = normalize(goodsRecovery.getName());
        // 更新商品名以保持一致性
        goodsRecovery.setName(goodsRecovery.getName());
        // 对商品名进行标准化处理
        goodsRecovery.setNormalizedName(normalizedGoodsName);
        QueryWrapper<GoodsRecovery> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("normalized_name", normalizedGoodsName)
                .eq("delete_flag", 0);
        if (goodsRecovery.getId() != null) {
            queryWrapper.ne("id", goodsRecovery.getId());
        }
        if (goodsRecovery.getId() != null) {
            goodsRecovery.setUpdateTime(new Date());
            goodsRecovery.setUpdateBy(principal.getUserId());
            return Result.upStatus(baseMapper.updateById(goodsRecovery));
        } else {
            goodsRecovery.setCreateBy(principal.getUserId());
            goodsRecovery.setCreateTime(new Date());
            return Result.upStatus(baseMapper.insert(goodsRecovery));
        }
    }

    @Override
    public Result updateGoodsRecovery(GoodsRecovery goodsRecovery) {
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return Result.error("该用户不存在或未登录");
        }
        GoodsRecovery goodsRecovery1 = baseMapper.selectById(goodsRecovery.getId());
        if (ObjectUtils.isEmpty(goodsRecovery1)) {
            return Result.error("该回收物品不存在");
        }
        if (goodsRecovery.getName() != null) {
            // 对商品名进行标准化处理
            String normalizedGoodsName = normalize(goodsRecovery.getName());
            // 更新商品名以保持一致性
            goodsRecovery.setName(goodsRecovery.getName());
            // 对商品名进行标准化处理
            goodsRecovery.setNormalizedName(normalizedGoodsName);
        }
//        int count = baseMapper.selectCount(new QueryWrapper<GoodsRecovery>()
//                .eq("name", goodsRecovery.getName())
//                .ne("id", goodsRecovery.getId())
//                .eq("delete_flag", 0));
//        if (count > 0) {
//            return Result.error("该回收物品名称已存在");
//        }
        goodsRecovery.setUpdateTime(new Date());
        goodsRecovery.setUpdateBy(principal.getUserId());
        return Result.upStatus(baseMapper.updateById(goodsRecovery));
    }

    @Override
    public Result deleteGoodsRecovery(Long id) {
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return Result.error("该用户不存在或未登录");
        }
        GoodsRecovery goodsRecovery = baseMapper.selectById(id);
        if (ObjectUtils.isEmpty(goodsRecovery)) {
            return Result.error("该回收物品不存在");
        }
        return Result.upStatus(baseMapper.deleteById(goodsRecovery.getId()));
    }

    // 辅助方法：标准化字符串（移除所有非字母数字字符并转换为小写）
    private String normalize(String input) {
        if (input == null || input.isEmpty()) {
            return "";
        }
        // 移除非字母数字字符，并转为小写
        return input.replaceAll(" ", "").toLowerCase();
    }

    @Override
    public Result getGoodsRecoveryList(Integer pageNum, Integer pageSize, String name, Long brandId) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        // 构建查询条件
        QueryWrapper<GoodsRecovery> queryWrapper = new QueryWrapper<>();
        boolean isSearchingByName = StringUtils.isNotBlank(name);
        if (isSearchingByName) {
            // 对用户输入进行标准化处理
            String normalizedSearchName = normalize(name);

            // 使用标准化后的名字进行模糊查询
            queryWrapper.like("normalized_name", normalizedSearchName);
        }
        if (brandId != null) {
            queryWrapper.eq("brand_id", brandId);
        }
        // 按照搜索次数降序排序
        queryWrapper.orderByDesc("search_count");

        // 构建参数Map，传递给XML中的SQL查询
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("brandId", brandId);
        params.put("queryWrapper", queryWrapper);

        // 查询
        List<GoodsRecovery> list = baseMapper.getGoodsRecoveryList(params);

        // 如果是通过名称搜索，并且结果列表非空，则更新searchCount
        if (isSearchingByName && !list.isEmpty()) {
            list.forEach(goodsRecovery -> {
                goodsRecovery.setSearchCount(goodsRecovery.getSearchCount() + 1);
                baseMapper.updateById(goodsRecovery);
            });
        }
        return Result.success().put("data", new PageInfo<>(list));
    }

    @Override
    public Result getGoodsRecoveryById(Long id) {
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return Result.error("该用户不存在或未登录");
        }
        GoodsRecovery goodsRecovery = baseMapper.selectById(id);
        if (ObjectUtils.isEmpty(goodsRecovery)) {
            return Result.error("该回收物品不存在");
        }
        return Result.success().put("data", goodsRecovery);
    }

    @Override
    public Result estimatedPriceByRecoveryId(Long recoveryId, Long userId) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("当前用户未登录，请登录");
        }
        if (user.getIsAuth() == 0) {
            return Result.error("当前用户未实名认证，请实名认证");
        }
        List<GoodsSpecifications> list = goodsSpecificationsDao.selectList(new QueryWrapper<GoodsSpecifications>()
                .eq("recovery_id", recoveryId)
                .eq("delete_flag", 0));
        BigDecimal totalPrice = BigDecimal.ZERO;
        if (!ObjectUtils.isEmpty(list)) {
            for (GoodsSpecifications goodsSpecifications : list) {
                totalPrice = totalPrice.add(goodsSpecifications.getPrice());
            }
        }
        GoodsRecoveryUser goodsRecoveryUser = new GoodsRecoveryUser();
        goodsRecoveryUser.setUserId(userId);
        goodsRecoveryUser.setRecoveryId(recoveryId);
        goodsRecoveryUser.setTotalPrice(totalPrice);
        int count = goodsRecoveryUserDao.insert(goodsRecoveryUser);
        if (count <= 0) {
            return Result.error("该回收物品估价失败");
        }
        return Result.success().put("data", totalPrice);
    }

    @Override
    public Result selectListBySpecifications(Long userId, Long id) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("当前用户未登录，请登录");
        }
        if (user.getIsAuth() == 0) {
            return Result.error("当前用户未实名认证，请实名认证");
        }
        List<GoodsSpecifications> list = goodsSpecificationsDao.selectList(new QueryWrapper<GoodsSpecifications>()
                .eq("recovery_id", id)
                .eq("delete_flag", 0));
        if (!ObjectUtils.isEmpty(list)) {
            return Result.success().put("data", list);
        }
        return Result.success().put("data", new ArrayList<>());
    }

    @Override
    public Result selectListByHistory() {
        return null;
    }

    @Override
    public Result getGoodsRecoveryListByBrandId(Integer pageNum, Integer pageSize, String name, Long brandId) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        // 构建查询条件
        QueryWrapper<GoodsRecovery> queryWrapper = new QueryWrapper<>();
        boolean isSearchingByName = StringUtils.isNotBlank(name);
        if (isSearchingByName) {
            // 对用户输入进行标准化处理
            String normalizedSearchName = normalize(name);

            // 使用标准化后的名字进行模糊查询
            queryWrapper.like("normalized_name", normalizedSearchName);
        }
        if (brandId != null) {
            queryWrapper.eq("brand_id", brandId);
        }
        // 按照搜索次数降序排序
        queryWrapper.orderByDesc("search_count");

        // 构建参数Map，传递给XML中的SQL查询
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("brandId", brandId);
        params.put("queryWrapper", queryWrapper);

        // 查询
        List<GoodsRecovery> list = baseMapper.getGoodsRecoveryListByBrandId(params);

        // 如果是通过名称搜索，并且结果列表非空，则更新searchCount
        if (isSearchingByName && !list.isEmpty()) {
            list.forEach(goodsRecovery -> {
                goodsRecovery.setSearchCount(goodsRecovery.getSearchCount() + 1);
                baseMapper.updateById(goodsRecovery);
            });
        }
        return Result.success().put("data", new PageInfo<>(list));
    }

    @Override
    public Result getRecoveryListByBrandId(Integer pageNum, Integer pageSize, String name, Long brandId) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        QueryWrapper<GoodsRecovery> queryWrapper = new QueryWrapper<>();
        if (brandId != null) {
            queryWrapper.eq("brand_id", brandId);
        }
        // 查询
        List<GoodsRecovery> list = baseMapper.selectRecoveryByBrandId(brandId);
        return Result.success().put("data", new PageInfo<>(list));
    }
}




